package com.grm.j001array;

public class MyArrayList {
    private Object[] array = new Object[]{};
    private int size = 0;
    // 集合元素个数
    public int size() {
        return size;
    }
    // 添加元素
    public void add(Object e) {
        if (array.length == 0) {
            array = new Object[10];
        }
        if (size == array.length) { // 容量达到最大时，扩容
            Object[] newArray = new Object[array.length * 2];
            for (int i = 0; i < array.length; i++) {
                newArray[i] = array[i];
            }
            array = newArray;
        }
        array[size] = e;
        size++;
    }
    // 移除index位置的元素
    public void delete(int index) {
        if (index < 0 || index >= array.length) {
            throw new ArrayIndexOutOfBoundsException("索引越界！");
        }
        // [2,1,3,4]   index = 1,后面的前移
        Object[] newArray = new Object[array.length];
        for (int i = 0; i + 1 <= array.length - 1; i++) {
            if (i < index) {
                newArray[i] = array[i];
            } else {
                newArray[i] = array[i + 1];
            }
        }
        array = newArray;
        size--;
    }

    public void print() {
        if (size == 0) {
            System.out.println("[]");
        }
        StringBuilder stringBuilder = new StringBuilder("[");
        for (int i = 0; i < size; i++) {
            if (i < size - 1) {
                stringBuilder.append(array[i]).append(",");
            } else {
                stringBuilder.append(array[i]).append("]");
            }
        }
        System.out.println(stringBuilder);
    }
}
